package com.payment.ktb.activity.main4;

import android.app.DatePickerDialog;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.android.volley.VolleyError;
import com.flyco.animation.BounceEnter.BounceTopEnter;
import com.flyco.animation.SlideExit.SlideTopExit;
import com.flyco.dialog.widget.popup.base.BasePopup;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.payment.ktb.Interface.HttpCallbackListener;
import com.payment.ktb.R;
import com.payment.ktb.activity.BaseActivity;
import com.payment.ktb.adapter.CustomerManageAdapter;
import com.payment.ktb.adapter.OrderCenterAdapter;
import com.payment.ktb.constants.ConstantsCustomer;
import com.payment.ktb.constants.ConstantsUser;
import com.payment.ktb.constants.HttpActions;
import com.payment.ktb.constants.HttpUrls;
import com.payment.ktb.model.CustomerManageEntity;
import com.payment.ktb.model.OrderCenterEntity;
import com.payment.ktb.model.OrderCenterFullEntity;
import com.payment.ktb.utils.AlertDialogUtils;
import com.payment.ktb.utils.HttpUtils;
import com.payment.ktb.utils.StringUtils;
import com.payment.ktb.utils.ToastUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by admin on 2017/12/4.
 */

public class CustomerManageActivity extends BaseActivity {


    @BindView(R.id.iv_customermanage_date_arror)
    ImageView iv_customermanage_date_arror;
    @BindView(R.id.iv_customermanage_status_arror)
    ImageView iv_customermanage_status_arror;
    @BindView(R.id.tv_customermanage_status)
    TextView tv_customermanage_status;
    @BindView(R.id.rl_customermanage_status)
    RelativeLayout rl_customermanage_status;


    @BindView(R.id.rl_customermanage_date_all)
    RelativeLayout rl_customermanage_date_all;
    @BindView(R.id.tv_customermanage_date_starttime)
    TextView tv_customermanage_date_starttime;
    @BindView(R.id.tv_customermanage_date_endtime)
    TextView tv_customermanage_date_endtime;

    @BindView(R.id.prlv_customermanage)
    PullToRefreshListView prlv_customermanage;


    String ts = null;
    String te = null;
    private CustomerManageActivity.SimpleCustomPopCustomerStatus mSimpleCustomPopCustomerStatus;
    private int page = 0;
    private String userStatus = "";
    private List<CustomerManageEntity> listDatas = new ArrayList<>();
    CustomerManageAdapter adapter;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_custommanage);
        initTitle("商户管理");
        ButterKnife.bind(this);

        initData();

        prlv_customermanage.setMode(PullToRefreshBase.Mode.BOTH);
        prlv_customermanage.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                //下拉刷新
                pullDownToRefresh();
            }
            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                pullUptoLoad();


            }
        });
        pullDownToRefresh();

    }

    private void initData() {

        mSimpleCustomPopCustomerStatus = new SimpleCustomPopCustomerStatus(mContext);
        // 设置下拉刷新加载文本
        prlv_customermanage.getLoadingLayoutProxy(true, false).setPullLabel("下拉刷新...");
        prlv_customermanage.getLoadingLayoutProxy(true, false).setReleaseLabel("放开刷新...");
        prlv_customermanage.getLoadingLayoutProxy(true, false).setRefreshingLabel("正在加载...");
        // 设置上拉加载文本
        prlv_customermanage.getLoadingLayoutProxy(false, true).setPullLabel("上拉刷新...");
        prlv_customermanage.getLoadingLayoutProxy(false, true).setReleaseLabel("放开刷新...");
        prlv_customermanage.getLoadingLayoutProxy(false, true).setRefreshingLabel("正在加载...");
    }





    private void pullDownToRefresh() {

        progressDialogUtils.showProgress();
        //构造传输参数
        page = 0;
        Map<String, String> map = new HashMap<String,String>();
        map.put("ts",ts);
        map.put("te",te);
        map.put("userStatus", userStatus);
        map.put("limit", "20");
        map.put("page", String.valueOf(page));
        //向服务器发送请求
        HttpUtils.HttpRequestByVollery(HttpUrls.URL, HttpActions.OrgChildUser, map, mQueue, new HttpCallbackListener() {
            @Override
            public void onFinish(String response) {

                try {
                    JSONObject jsonObject = new JSONObject(response);

                    progressDialogUtils.dismissProgress();
                    prlv_customermanage.onRefreshComplete();
                    listDatas.clear();

                    //data
                    listDatas = new Gson().fromJson(jsonObject.getJSONArray("records").toString(), new TypeToken<List<CustomerManageEntity>>() {}.getType());
                    if (listDatas == null || listDatas.isEmpty()) {
                        listDatas = new ArrayList<CustomerManageEntity>();
                        ToastUtils.showToast("没有数据！");
                    }
                    //adapter
                    adapter = new CustomerManageAdapter(mContext, listDatas);
                    //bind
                    prlv_customermanage.setAdapter(adapter);

                } catch (JSONException e) {
                    e.printStackTrace();
                    AlertDialogUtils.showAlertDialog(mContext, getResources().getString(R.string.json_parse_error));
                }

            }
            @Override
            public void onError(VolleyError volleyError) {
                progressDialogUtils.dismissProgress();
                prlv_customermanage.onRefreshComplete();
                AlertDialogUtils.showAlertDialog(mContext, volleyError.getMessage());
            }
        });
    }






    private void pullUptoLoad() {

        progressDialogUtils.showProgress();
        //构造传输参数
        page = page + 1;
        Map<String, String> map = new HashMap<String,String>();
        map.put("ts",ts);
        map.put("te",te);
        map.put("userStatus", userStatus);
        map.put("limit", "20");
        map.put("page", String.valueOf(page));
        //向服务器发送请求
        HttpUtils.HttpRequestByVollery(HttpUrls.URL, HttpActions.OrgChildUser, map, mQueue, new HttpCallbackListener() {
            @Override
            public void onFinish(String response) {

                try {

                    JSONObject jsonObject = new JSONObject(response);

                    progressDialogUtils.dismissProgress();
                    prlv_customermanage.onRefreshComplete();
                    //data
                    List<CustomerManageEntity> customerManages = null;
                    customerManages = new Gson().fromJson(jsonObject.getJSONArray("records").toString(), new TypeToken<List<CustomerManageEntity>>() {}.getType());

                    if (customerManages != null && !customerManages.isEmpty()) {
                        //adapter
                        listDatas.addAll(customerManages);
                        adapter.notifyDataSetChanged();
                    }else {
                        ToastUtils.showToast("没有更多数据啦！");
                    }


                } catch (JSONException e) {
                    e.printStackTrace();
                    AlertDialogUtils.showAlertDialog(mContext, getResources().getString(R.string.json_parse_error));
                }

            }
            @Override
            public void onError(VolleyError volleyError) {
                progressDialogUtils.dismissProgress();
                prlv_customermanage.onRefreshComplete();
                AlertDialogUtils.showAlertDialog(mContext, volleyError.getMessage());
            }
        });

    }




    @OnClick({R.id.rl_customermanage_date,R.id.rl_customermanage_status,R.id.rl_customermanage_research,R.id.rl_customermanage_date_delete,
    R.id.tv_customermanage_date_starttime,R.id.tv_customermanage_date_endtime,R.id.btn_customermanage_date_confirm})
    public void clickEvent(View view) {

        switch (view.getId()) {

            //开始时间
            case R.id.tv_customermanage_date_starttime:
                showStartDateDialog();
                break;

            //结束时间
            case R.id.tv_customermanage_date_endtime:
                showEndDateDialog();
                break;


            //弹出时间
            case R.id.rl_customermanage_date:
                if (rl_customermanage_date_all.getVisibility() == View.VISIBLE) {
                    rl_customermanage_date_all.setVisibility(View.GONE);
                    iv_customermanage_date_arror.setImageResource(R.mipmap.order_arror_down);
                }else {

                    if (TextUtils.isEmpty(tv_customermanage_date_starttime.getText().toString())) {
                        Calendar calendar = Calendar.getInstance();
                        calendar.setTime(new Date());
                        calendar.add(Calendar.DATE,-7);
                        tv_customermanage_date_starttime.setText(new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime()));
                        tv_customermanage_date_endtime.setText(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
                        ts = new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime()) + " 00:00:00";
                        te = new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + " 23:59:59";
                    }

                    rl_customermanage_date_all.setVisibility(View.VISIBLE);
                    iv_customermanage_date_arror.setImageResource(R.mipmap.order_arror_up);

                }
                break;


            //隐藏时间
            case R.id.rl_customermanage_date_delete:
                rl_customermanage_date_all.setVisibility(View.GONE);
                iv_customermanage_date_arror.setImageResource(R.mipmap.order_arror_down);
                break;


            //时间确认
            case R.id.btn_customermanage_date_confirm:
                rl_customermanage_date_all.setVisibility(View.GONE);
                iv_customermanage_date_arror.setImageResource(R.mipmap.order_arror_down);
                pullDownToRefresh();
                break;




            //类型
            case R.id.rl_customermanage_status:


                if (mSimpleCustomPopCustomerStatus.isShowing()){
                    mSimpleCustomPopCustomerStatus.dismiss();
                    iv_customermanage_status_arror.setImageResource(R.mipmap.order_arror_down);
                }else {
                    mSimpleCustomPopCustomerStatus
                            .offset(0, 5)
                            .anchorView(rl_customermanage_status)
                            .gravity(Gravity.BOTTOM)
                            .showAnim(new BounceTopEnter())
                            .dismissAnim(new SlideTopExit())
                            .dimEnabled(false)
                            .show();
                    iv_customermanage_status_arror.setImageResource(R.mipmap.order_arror_up);
                }

                break;

            //搜索
            case R.id.rl_customermanage_research:
                startActivity(CustomerResearchActivity.class);
                break;


        }



    }





    /**
     *
     */
    private void showStartDateDialog() {

        ToastUtils.showToast("请选择开始时间！");
        new DatePickerDialog(mContext, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                String time = String.format("%d-%d-%d",year,monthOfYear + 1,dayOfMonth);
                ts = time + " 00:00:00";
                tv_customermanage_date_starttime.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
            }
        }, Calendar.getInstance().get(Calendar.YEAR),Calendar.getInstance().get(Calendar.MONTH),Calendar.getInstance().get(Calendar.DAY_OF_MONTH)).show();
    }



    /**
     *
     */
    private void showEndDateDialog() {

        ToastUtils.showToast("请选择结束时间！");
        new DatePickerDialog(mContext, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                String time = String.format("%d-%d-%d",year,monthOfYear + 1,dayOfMonth);
                te = time + " 23:59:59";
                tv_customermanage_date_endtime.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
            }
        }, Calendar.getInstance().get(Calendar.YEAR),Calendar.getInstance().get(Calendar.MONTH),Calendar.getInstance().get(Calendar.DAY_OF_MONTH)).show();
    }





    class SimpleCustomPopCustomerStatus extends BasePopup<CustomerManageActivity.SimpleCustomPopCustomerStatus> {

        @BindView(R.id.rl_customermanage_status_item1)
        RelativeLayout rl_customermanage_status_item1;
        @BindView(R.id.rl_customermanage_status_item2)
        RelativeLayout rl_customermanage_status_item2;
        @BindView(R.id.rl_customermanage_status_item3)
        RelativeLayout rl_customermanage_status_item3;
        @BindView(R.id.rl_customermanage_status_item4)
        RelativeLayout rl_customermanage_status_item4;
        @BindView(R.id.iv_customermanage_status_item1)
        ImageView iv_customermanage_status_item1;
        @BindView(R.id.iv_customermanage_status_item2)
        ImageView iv_customermanage_status_item2;
        @BindView(R.id.iv_customermanage_status_item3)
        ImageView iv_customermanage_status_item3;
        @BindView(R.id.iv_customermanage_status_item4)
        ImageView iv_customermanage_status_item4;
        @BindView(R.id.tv_customermanage_status_item1)
        TextView tv_customermanage_status_item1;
        @BindView(R.id.tv_customermanage_status_item2)
        TextView tv_customermanage_status_item2;
        @BindView(R.id.tv_customermanage_status_item3)
        TextView tv_customermanage_status_item3;
        @BindView(R.id.tv_customermanage_status_item4)
        TextView tv_customermanage_status_item4;






        public SimpleCustomPopCustomerStatus(Context context) {
            super(context);
            setCanceledOnTouchOutside(false);
        }

        @Override
        public View onCreatePopupView() {
            View inflate = View.inflate(mContext, R.layout.dialog_customermanage_customerstatus, null);
            ButterKnife.bind(this, inflate);
            return inflate;
        }

        @Override
        public void setUiBeforShow() {
            rl_customermanage_status_item1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    iv_customermanage_status_item1.setVisibility(View.VISIBLE);
                    iv_customermanage_status_item2.setVisibility(View.GONE);
                    iv_customermanage_status_item3.setVisibility(View.GONE);
                    iv_customermanage_status_item4.setVisibility(View.GONE);
                    mSimpleCustomPopCustomerStatus.dismiss();
                    iv_customermanage_status_arror.setImageResource(R.mipmap.order_arror_down);
                    tv_customermanage_status.setText(tv_customermanage_status_item1.getText());
                    userStatus = "";
                    pullDownToRefresh();

                }
            });
            rl_customermanage_status_item2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    iv_customermanage_status_item2.setVisibility(View.VISIBLE);
                    iv_customermanage_status_item1.setVisibility(View.GONE);
                    iv_customermanage_status_item3.setVisibility(View.GONE);
                    iv_customermanage_status_item4.setVisibility(View.GONE);
                    mSimpleCustomPopCustomerStatus.dismiss();
                    iv_customermanage_status_arror.setImageResource(R.mipmap.order_arror_down);
                    tv_customermanage_status.setText(tv_customermanage_status_item2.getText());
                    userStatus = ConstantsCustomer.INIT.getCode() + "";
                    pullDownToRefresh();
                }
            });
            rl_customermanage_status_item3.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    iv_customermanage_status_item3.setVisibility(View.VISIBLE);
                    iv_customermanage_status_item1.setVisibility(View.GONE);
                    iv_customermanage_status_item2.setVisibility(View.GONE);
                    iv_customermanage_status_item4.setVisibility(View.GONE);
                    mSimpleCustomPopCustomerStatus.dismiss();
                    iv_customermanage_status_arror.setImageResource(R.mipmap.order_arror_down);
                    tv_customermanage_status.setText(tv_customermanage_status_item3.getText());
                    userStatus = ConstantsCustomer.PASS.getCode() + "";
                    pullDownToRefresh();

                }
            });
            rl_customermanage_status_item4.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    iv_customermanage_status_item4.setVisibility(View.VISIBLE);
                    iv_customermanage_status_item1.setVisibility(View.GONE);
                    iv_customermanage_status_item2.setVisibility(View.GONE);
                    iv_customermanage_status_item3.setVisibility(View.GONE);
                    mSimpleCustomPopCustomerStatus.dismiss();
                    iv_customermanage_status_arror.setImageResource(R.mipmap.order_arror_down);
                    tv_customermanage_status.setText(tv_customermanage_status_item4.getText());
                    userStatus = ConstantsCustomer.FAIL.getCode() + "";
                    pullDownToRefresh();
                }
            });
        }
    }












}
